package com.midea.ai.air.ui.more;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.midea.ai.air.R;
import com.midea.ai.air.common.ActionBarBackFragment;
import com.midea.ai.air.common.BaseActivity;
import com.midea.ai.air.common.ConsVal;
import com.midea.ai.air.common.Constant;
import com.midea.ai.air.ui.home.MainActivityNew;
import com.midea.ai.air.utils.ComUtils;
import com.midea.ai.air.utils.zxing.CaptureActivity;
import com.midea.ai.air.view.AlertCenterDialog;
import com.midea.ai.air.view.LoadingDialog;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by ouyangdi on 2016/4/16.
 * 更多->我的家庭Activity
 */
public class MoreFamilyAddMemberActivity extends BaseActivity {

    private final static int SCANNIN_GREQUEST_CODE = 0x001;
    public static final int FIND_SUCCESS = 1;
    public static final int SEND_SUCCESS = 2;
    public final static String SCANNING_REQUEST_CODE_FAMILY = "ADD_FAMILY_MEMBER";

    ActionBarBackFragment mActionBar;
    private TextView mActionBarRightBtn;
    private String mActionBarTitle;
    private String mStrRightBtn;

    private EditText mInputMember;
    private ImageView mIvCodeScan; //二维码扫描
    private String mStrAccount;
    private LoadingDialog mDialog;

    private Timer mTimer;

    class TaskFind extends TimerTask {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(FIND_SUCCESS);
        }
    }

    class TaskInvite extends TimerTask {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(SEND_SUCCESS);
        }
    }

    ;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FIND_SUCCESS) {
                mDialog.setLoadingText("正在发送邀请…");
            } else if (msg.what == SEND_SUCCESS) {
                mDialog.stopProgressAnim(true);
                mDialog.setCanceledOnTouchOutside(true);
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer.purge();
                    mTimer = null;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_more_family_add_member);

        getIntentData();
        initView();
    }

    /**
     * 获取Intent携带的数据
     */
    private void getIntentData() {
        mActionBarTitle = getIntent().getStringExtra(ConsVal.KEY_TITLE);
        mStrRightBtn = getIntent().getStringExtra(ConsVal.KEY_ARG);
    }

    private void initView() {
        initActionBar();

        mInputMember = (EditText) findViewById(R.id.input_invite_member);
        mInputMember.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mActionBarRightBtn.setAlpha(0.25f);
                    mActionBarRightBtn.setClickable(false);
                    return;
                }
                mActionBarRightBtn.setClickable(true);
                mActionBarRightBtn.setAlpha(1f);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mIvCodeScan = (ImageView) findViewById(R.id.imgView_code_scan);
        mIvCodeScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(MoreFamilyAddMemberActivity.this, CaptureActivity.class));

                Intent intent = new Intent();
                intent.setClass(MoreFamilyAddMemberActivity.this, CaptureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                Bundle bundle = new Bundle();
                bundle.putString(MainActivityNew.SCAN_THE_QR_CODE_TAG, MainActivityNew.SCANNING_REQUEST_CODE_RESULT);
                intent.putExtras(bundle);
                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    mInputMember.setText(bundle.getString("result"));
                    //显示
//                    mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                }
                break;
        }
    }

    private void initActionBar() {
        FrameLayout mBarLayout = (FrameLayout) findViewById(R.id.bar_parent);
        ViewGroup.LayoutParams LP = mBarLayout.getLayoutParams();
        LP.height = Constant.getTopMargin() + getResources().getDimensionPixelSize(R.dimen.height_44dp);
        mBarLayout.setLayoutParams(LP);
        mActionBar = (ActionBarBackFragment) getSupportFragmentManager().findFragmentById(R.id.bar_fragment);

        mActionBarRightBtn = mActionBar.getTvBarRight();
        mActionBarRightBtn.setText(mStrRightBtn);
        mActionBarRightBtn.setVisibility(View.VISIBLE);
        mActionBarRightBtn.setAlpha(0.25f);
        mActionBarRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStrAccount = mInputMember.getText().toString();
                new AlertCenterDialog(MoreFamilyAddMemberActivity.this).builder().setTitle(getString(R.string.air_more_family_add_family_member))
                        .setMsg(getString(R.string.air_more_family_add_msg) + mStrAccount + getString(R.string.air_more_family_change_msg_end))
                        .setPositiveButton("", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDialog = new LoadingDialog(MoreFamilyAddMemberActivity.this).builder();
                                mDialog.setLoadingText("正在寻找用户…");
                                mDialog.setPosMsg("邀请发送成功");
                                mDialog.setNegMsg("邀请发送失败");
                                mDialog.setCanceledOnTouchOutside(false);
                                mDialog.show();
                                mTimer = new Timer();
                                mTimer.schedule(new TaskFind(), 2000);
                                mTimer.schedule(new TaskInvite(), 4000);
                            }
                        })
                        .setNegativeButton("", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).show();
            }
        });
        mActionBarRightBtn.setClickable(false);

        mActionBar.getBackButton().setVisibility(View.GONE);
        mActionBar.getTvBarLeft().setVisibility(View.VISIBLE);
        mActionBar.getTvTitle().setText(mActionBarTitle);
    }

    //点击EditText以外的区域隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (ComUtils.isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
